﻿using System.Linq;
using System.Linq.Expressions;
using Simple.Common.Authentication;
using Simple.Repository.Models.ClassRoom;
using Simple.Services.System.FileInfo;
using static Simple.Services.ClassDynamicCreateOrUpdateModel;

namespace Simple.Services.System.ClassRoom
{
    public class ClassDynamicService : BusinessBaseService
    {
        private readonly SimpleDbContext _context;
        private readonly CacheService _cacheService;
        private readonly FileInfoService _fileInfoService;

        public ClassDynamicService(SimpleDbContext context,
                           ISimpleService services,
                           CacheService cacheService,
                           FileInfoService fileInfoService) : base(services)
        {
            _context = context;
            _cacheService = cacheService;
            _fileInfoService = fileInfoService;
        }

        public async Task<ClassDynamicOutputModel> GetAsync(Guid? classDynamicId)
        {
            if (!classDynamicId.HasValue)
            {
                throw AppResultException.Status409Conflict("参数错误,班级动态Id参数不能为Null!");
            } 
            var classDynamicInfo = await _context.Set<ClassDynamic>().Include(c => c.Images).Include(c => c.LeaveMessages).FirstOrDefaultAsync(c => c.Id == classDynamicId);

            if (classDynamicInfo == null)
            {
                throw AppResultException.Status409Conflict("未找到班级动态相关数据!");
            }

            var outResult = MapperHelper.Map<ClassDynamicOutputModel>(classDynamicInfo);
            var _classIdList = classDynamicInfo.ClassIds?.Split(",")?.ToList()?.Distinct()?.Select(c => Guid.Parse(c));
            var classList = _context.Set<SysClasses>().Where(c => _classIdList.Contains(c.Id))?.ToList();
            outResult.ClassList = classList?.Where(c => _classIdList.Contains(c.Id))?.ToList()?.Select(c => new ClassDynamicSysClassesDto { ClassId = c.Id.ToString(), ClassName = c.Name })?.ToList() ?? new List<ClassDynamicSysClassesDto>();
            var chidrenInfo = await _context.Set<Childrens>().FirstOrDefaultAsync(c => outResult.RelationshipChildrenId == c.Id);
            outResult.RelationshipChildrenName = chidrenInfo?.Name;

            return outResult;
        }

        public async Task<PageResultModel<ClassDynamicOutputModel>> GetPageAsync(ClassDynamicQueryPageInputModel input)
        {
            if (_currentUser == null)
            {
                throw AppResultException.Status409Conflict("登录已过期,请重新登录!");
            }

            var classIdList = new List<string>();
            var currentClassAuthorizationList = await GetClassAuthorizationInfo();
            if (currentClassAuthorizationList != null && currentClassAuthorizationList.Any())
            {
                classIdList = currentClassAuthorizationList.Select(c => c.Id.ToString() ?? string.Empty).Where(c => !string.IsNullOrWhiteSpace(c)).ToList();
            }

            if (classIdList == null || !classIdList.Any())
            {
                return new PageResultModel<ClassDynamicOutputModel>() { Rows = new List<ClassDynamicOutputModel>() };
            }

            var result = new PageResultModel<ClassDynamicOutputModel>();
            var query = await OrganizationFilter(_context.Set<ClassDynamic>().Include(c => c.Images).Include(c => c.LeaveMessages));

            if (!string.IsNullOrEmpty(input.ContentKey))
            {
                query = query.Where(m => EF.Functions.Like(m.Content, $"%{input.ContentKey}%"));
            }

            if (!string.IsNullOrWhiteSpace(input.ClassId))
            {
                query = query.Where(m => m.ClassIds.Contains(input.ClassId));
            }

            Expression<Func<ClassDynamic, bool>>? multipleSampleCodeConditions = null;
            if (classIdList.Any())
            {
                multipleSampleCodeConditions = classIdList.Select(no => (Expression<Func<ClassDynamic, bool>>)(x => EF.Functions.Like(x.ClassIds, $"%{no}%")))?.ConcatOr();
            }

            if (multipleSampleCodeConditions != null)
            {
                query = query.Where(multipleSampleCodeConditions);
            }

            // 排序
            query = query.OrderByDescending(m => m.CreatedTime);

            // 获取总数量
            result.TotalRows = await query.CountAsync();

            // 分页查询
            query = query.Page(input.PageNo, input.PageSize);
            var classDynamicOutResultList = await query.ToListAsync();
            result.Rows = MapperHelper.Map<List<ClassDynamicOutputModel>>(classDynamicOutResultList);
            if (classDynamicOutResultList != null && classDynamicOutResultList.Any())
            {
                var _classIdList = string.Join(",", classDynamicOutResultList.Select(c => c.ClassIds)).Split(",")?.ToList()?.Distinct()?.Select(c => Guid.Parse(c));
                var classList = _context.Set<SysClasses>().Where(c => _classIdList.Contains(c.Id))?.ToList();
                var _childIdList = classDynamicOutResultList?.Where(c => c.RelationshipChildrenId.HasValue).Select(c => c.RelationshipChildrenId)?.ToList();
                List<Childrens>? chidrenList = new List<Childrens>();
                if (_childIdList != null && _childIdList.Any())
                {
                    chidrenList = _context.Set<Childrens>().Where(c => _childIdList.Contains(c.Id))?.ToList();
                }
                result.Rows?.ForEach(item =>
                {
                    item.RelationshipChildrenName = chidrenList?.FirstOrDefault(p => p.Id == item.RelationshipChildrenId)?.Name ?? string.Empty;
                    var currentClassIdList = classDynamicOutResultList?.FirstOrDefault(c => c.Id == item.Id)?.ClassIds?.Split(',')?.ToList()?.Select(c => Guid.Parse(c));
                    if (currentClassIdList != null && currentClassIdList.Any())
                    {
                        item.ClassList = classList?.Where(c => currentClassIdList.Contains(c.Id))?.ToList()?.Select(c => new ClassDynamicSysClassesDto { ClassId = c.Id.ToString(), ClassName = c.Name })?.ToList() ?? new List<ClassDynamicSysClassesDto>();
                    }
                });
            }

            result.SetPage(input);
            result.CountTotalPage();

            return result;
        }

        public async Task<PageResultModel<MoveClassDynamicOutputModel>> MoveGetPageAsync(ClassDynamicQueryPageInputModel input)
        {
            return await CommonMoveGetPageAsync(input, false, 1);
        }

        public async Task<int> AddAsync(ClassDynamicCreateOrUpdateModel model)
        {
            if (model == null)
            {
                throw AppResultException.Status409Conflict("参数不能为Null!");
            }

            if (string.IsNullOrWhiteSpace(model.Content) && (model.ImageList == null || !model.ImageList.Any()))
            {
                throw AppResultException.Status409Conflict("请输入发布内容，或者上传图片!");
            }

            if (model.ClassIdList == null || !model.ClassIdList.Any())
            {
                throw AppResultException.Status409Conflict("请选择发布班级!");
            }

            var images = new List<ClassDynamicImage>();
            if (model.ImageList != null && model.ImageList.Any())
            {
                foreach (var file in model.ImageList)
                {
                    var fileId = await _fileInfoService.UploadAsync(new FileInfo.Models.FileInfoInputModel { BusinessType = FileSource.ClassDynamics, File = file });
                    images.Add(new ClassDynamicImage { FiledId = fileId, FileName = file.FileName, FileSize = GetFileSize(file.Length) });
                }
            }

            return await CreateAsync(new ClassDynamicCreateOrUpdateCommandModel { Id = model.Id, ClassIdList = model.ClassIdList, Content = model.Content }, images);
        }

        public async Task<int> MoveAddAsync(MoveClassDynamicCreateOrUpdateModel model)
        {
            if (model == null)
            {
                throw AppResultException.Status409Conflict("参数不能为Null!");
            }

            if (string.IsNullOrWhiteSpace(model.Content) && (model.ImageIdList == null || !model.ImageIdList.Any()))
            {
                throw AppResultException.Status409Conflict("请输入发布内容，或者上传图片!");
            }

            var loginTypeValue = _currentUser?.FindClaimValue(SimpleClaimTypes.LoginType);
            LoginType? loginType = null;
            if (!string.IsNullOrWhiteSpace(loginTypeValue))
            {
                loginType = (LoginType)Enum.Parse(typeof(LoginType), loginTypeValue);
            }

            if (loginType == LoginType.GardenSide || loginType == null)
            {
                if (model.ClassIdList == null || !model.ClassIdList.Any())
                {
                    throw AppResultException.Status409Conflict("请选择发布班级!");
                }
            }

            List<ClassDynamicImage> images = new List<ClassDynamicImage>();
            if (model.ImageIdList != null && model.ImageIdList.Any())
            {
                var files = await _fileInfoService.GetFilesByIdListAsync(model.ImageIdList);
                images = files?.Select(file => new ClassDynamicImage { FiledId = file.Id, FileName = file.FileName, FileSize = file.FileSize ?? String.Empty })?.ToList() ?? new List<ClassDynamicImage>();
            }

            return await CreateAsync(new ClassDynamicCreateOrUpdateCommandModel { Id = model.Id, ClassIdList = model.ClassIdList, Content = model.Content }, images);
        }

        public async Task<int> CreateAsync(ClassDynamicCreateOrUpdateCommandModel model, List<ClassDynamicImage> images)
        {
            var loginTypeValue = _currentUser?.FindClaimValue(SimpleClaimTypes.LoginType);
            LoginType? loginType = null;
            if (!string.IsNullOrWhiteSpace(loginTypeValue))
            {
                loginType = (LoginType)Enum.Parse(typeof(LoginType), loginTypeValue);
            }

            if (loginType != LoginType.ParentSide || loginType == null)
            {
                if (model.ClassIdList != null && model.ClassIdList.Any())
                {
                    var currentClassAuthorizationList = await GetClassAuthorizationInfo();
                    var classIdList = new List<Guid>();
                    if (currentClassAuthorizationList != null && currentClassAuthorizationList.Any())
                    {
                        classIdList = currentClassAuthorizationList.Select(c => c.Id.Value).Where(c => c != default(Guid)).ToList();
                    }

                    var noAuthClassList = model.ClassIdList.Except(classIdList);
                    if (noAuthClassList != null && noAuthClassList.Any())
                    {
                        throw AppResultException.Status409Conflict("包含未授权的班级，操作失败!");
                    }
                }
            }
            else
            {
                var currentAuthClassIdList = _currentUser?.FindClaimValue(SimpleClaimTypes.ClassesId)?.Split(',')?.Where(p => !string.IsNullOrWhiteSpace(p))?.Select(c => Guid.Parse(c));
                if (currentAuthClassIdList == null || !currentAuthClassIdList.Any())
                {
                    throw AppResultException.Status409Conflict("当前登录家长获取班级失败，请重新登录后再试!");
                }

                model.ClassIdList = currentAuthClassIdList?.ToList();
            }

            var classDynamicInfo = MapperHelper.Map<ClassDynamic>(model);
            classDynamicInfo.CreateUserName = _currentUser?.Name ?? String.Empty;
            classDynamicInfo.LoginType = loginType?.GetHashCode();
            var childIdValue = _currentUser?.FindClaimValue(SimpleClaimTypes.ChildId);
            Guid.TryParse(childIdValue, out Guid chidrenId);
            classDynamicInfo.RelationshipChildrenId = chidrenId;
            var relationshipValue = _currentUser?.FindClaimValue(SimpleClaimTypes.Relationship);
            if (!string.IsNullOrWhiteSpace(relationshipValue))
            {
                Enum.TryParse(typeof(EnumParentRelationship), relationshipValue, out var _relationshipValue);
                if (_relationshipValue != null)
                {
                    classDynamicInfo.Relationship = ((EnumParentRelationship)_relationshipValue).GetHashCode();
                }
            }

            if (images != null && images.Any())
            {
                classDynamicInfo.Images = images;
            }

            classDynamicInfo.ClassIds = string.Join(",", model.ClassIdList?.Select(c => c.ToString())?.ToList() ?? new List<string>());
            await _context.AddAsync(classDynamicInfo);
            return await _context.SaveChangesAsync();
        }

        private string GetFileSize(long size)
        {
            var num = 1024.00;
            if (size < num)
                return size + " B";
            if (size < Math.Pow(num, 2))
                return (size / num).ToString("f2") + " KB";
            if (size < Math.Pow(num, 3))
                return (size / Math.Pow(num, 2)).ToString("f2") + " MB";
            if (size < Math.Pow(num, 4))
                return (size / Math.Pow(num, 3)).ToString("f2") + " GB";
            return (size / Math.Pow(num, 4)).ToString("f2") + " TB";
        }

        public async Task<int> UpdateAsync(ClassDynamicCreateOrUpdateModel model)
        {
            if (!model.Id.HasValue)
            {
                throw AppResultException.Status409Conflict("参数错误,班级Id参数不能为Null!");
            }

            var classDynamicInfo = await _context.Set<ClassDynamic>().Include(c => c.Images)
                .Where(m => model.Id == m.Id)
                .FirstOrDefaultAsync();

            if (classDynamicInfo == null)
            {
                throw AppResultException.Status404NotFound("未找到班级相关数据，更新失败！");
            }

            if (classDynamicInfo?.Images != null && classDynamicInfo.Images.Any())
            {
                _context.RemoveRange(classDynamicInfo.Images);
            }

            var images = new List<ClassDynamicImage>();
            if (model.ImageList != null && model.ImageList.Any())
            {
                foreach (var file in model.ImageList)
                {
                    var fileId = await _fileInfoService.UploadAsync(new FileInfo.Models.FileInfoInputModel { BusinessType = FileSource.ClassDynamics, File = file });
                    images.Add(new ClassDynamicImage { FiledId = fileId, FileName = file.FileName, FileSize = GetFileSize(file.Length) });
                }

                if (images != null && images.Any())
                {
                    classDynamicInfo.Images = images;
                }
            }

            classDynamicInfo.Content = model.Content;
            classDynamicInfo.ClassIds = string.Join(",", model.ClassIdList?.Select(c => c.ToString())?.ToList() ?? new List<string>());
            _context.Update(classDynamicInfo);
            int ret = await _context.SaveChangesAsync();

            if (ret == 0)
            {
                throw AppResultException.Status200OK("更新失败，更新记录数为0");
            }

            return ret;
        }

        public async Task<int> MoveUpdateAsync(MoveClassDynamicCreateOrUpdateModel model)
        {
            if (model == null || !model.Id.HasValue)
            {
                throw AppResultException.Status409Conflict("参数错误,班级Id参数不能为Null!");
            }

            var classDynamicInfo = await _context.Set<ClassDynamic>().Include(c => c.Images)
                .Where(m => model.Id == m.Id)
                .FirstOrDefaultAsync();

            if (classDynamicInfo == null)
            {
                throw AppResultException.Status404NotFound("未找到班级相关数据，更新失败！");
            }

            if (classDynamicInfo?.Images != null && classDynamicInfo.Images.Any())
            {
                _context.RemoveRange(classDynamicInfo.Images);
            }

            var images = new List<ClassDynamicImage>();
            if (model.ImageIdList != null && (model.ImageList?.Any() ?? false))
            {
                var files = await _fileInfoService.GetFilesByIdListAsync(model.ImageIdList);
                images = files?.Select(file => new ClassDynamicImage { FiledId = file.Id, FileName = file.FileName, FileSize = file.FileSize ?? String.Empty })?.ToList();
            }


            if (classDynamicInfo != null)
            {
                if (classDynamicInfo.Images != null && images != null && images.Any())
                {
                    classDynamicInfo.Images?.AddRange(images);
                }

                classDynamicInfo.Content = model?.Content ?? string.Empty;
                classDynamicInfo.ClassIds = string.Join(",", model?.ClassIdList?.Select(c => c.ToString())?.ToList() ?? new List<string>());
                _context.Update(classDynamicInfo);
            }

            int ret = await _context.SaveChangesAsync();

            if (ret == 0)
            {
                throw AppResultException.Status200OK("更新记录数为0");
            }

            return ret;
        }

        public async Task<int> DeleteAsync(List<Guid?> ids)
        {
            if (ids == null || !ids.Any())
            {
                throw AppResultException.Status409Conflict("参数错误,班级动态Id参数不能为Null!");
            }

            var classDynamicOutResultList = await _context.Set<ClassDynamic>().Include(c => c.Images).Include(c => c.LeaveMessages)
                .Where(m => ids.Contains(m.Id))
                .ToListAsync();

            if (classDynamicOutResultList == null || !classDynamicOutResultList.Any())
            {
                throw AppResultException.Status404NotFound("未找到班级动态相关数据，删除失败！");
            }

            // 先更新数据库
            _context.RemoveRange(classDynamicOutResultList);
            int ret = await _context.SaveChangesAsync();
            if (ret == 0)
            {
                throw AppResultException.Status200OK("更新记录数为0");
            }

            return ret;
        }

        public async Task<List<ClassDynamicOutputModel>> GetAll()
        {
            var query = await OrganizationFilter(_context.Set<ClassDynamic>());
            var result = await query.ToListAsync();
            if (result == null || !result.Any())
            {
                return new List<ClassDynamicOutputModel>();
            }

            return MapperHelper.Map<List<ClassDynamicOutputModel>>(result) ?? new List<ClassDynamicOutputModel>();
        }

        /// <summary>
        /// 获取当前登录用户授权的班级
        /// </summary>
        /// <returns></returns>
        public async Task<List<ClassesModel>> GetClassAuthorizationInfo()
        {
            var query = await OrganizationFilter(_context.Set<SysClasses>());
            var _IsWhetherTheDirector = false; // 当前是否园长登录
            var lstRole = _context.Set<SysRole>().AsQueryable().Where(p => _currentUser.Roles.Contains(p.Id.ToString())).Select(p => p.Name).ToList();
            if (lstRole.Any(p => p == "园长"))
            {
                _IsWhetherTheDirector = true;
            }

            if (!_currentUser.IsSuperAdmin && !_IsWhetherTheDirector)
            {
                query = query.Where(c => c.TeacherIds.Contains(_currentUser.UserId.ToString()));
            }

            var authorizationClassList = await query.ToListAsync();
            if (authorizationClassList == null || !authorizationClassList.Any())
            {
                return new List<ClassesModel>();
            }

            return MapperHelper.Map<List<ClassesModel>>(authorizationClassList);
        }

        /// <summary>
        /// 屏蔽或恢复
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> ChangeStatus(ChangeStatusModel model)
        {
            if (!model.Id.HasValue || !model.Status.HasValue)
            {
                throw AppResultException.Status409Conflict("参数错误,班级动态Id或状态不能为空！");
            }

            if (model.Status != 1 && model.Status != 2)
            {
                throw AppResultException.Status409Conflict("状态值错误!");
            }

            var classDynamicInfo = await _context.Set<ClassDynamic>().FirstOrDefaultAsync(c => c.Id == model.Id);

            if (classDynamicInfo == null)
            {
                throw AppResultException.Status409Conflict("未找到班级动态相关数据!");
            }

            classDynamicInfo.State = model.Status.Value;
            _context.Update(classDynamicInfo);
            int ret = await _context.SaveChangesAsync();

            if (ret == 0)
            {
                throw AppResultException.Status200OK("更新记录数为0");
            }

            return ret;
        }

        /// <summary>
        /// 留言
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<int> LeaveMessages(ClassDynamicLeaveMessagesDto input)
        {
            if (_currentUser == null)
            {
                throw AppResultException.Status409Conflict("登录已过期，请重新登录!");
            }

            if (input == null || String.IsNullOrWhiteSpace(input.Content) || !input.ClassDynamicId.HasValue)
            {
                throw AppResultException.Status409Conflict("参数错误,请检查留言内容、班级动态Id是否为Null!");
            }

            var classDynamicInfo = await (await OrganizationFilter(_context.Set<ClassDynamic>().Include(c => c.LeaveMessages))).FirstOrDefaultAsync(c => c.Id == input.ClassDynamicId);

            if (classDynamicInfo == null)
            {
                throw AppResultException.Status409Conflict("未找到班级动态相关数据!");
            }

            var entity = new ClassDynamicLeaveMessage();
            entity.LeaveMessageContent = input.Content;
            entity.LeaveMessageUserName = _currentUser?.Name ?? String.Empty;
            entity.ClassDynamicId = input.ClassDynamicId;
            entity.LeaveMessageTime = DateTime.Now;
            entity.LeaveMessageUserId = _currentUser?.FindClaimValue(SimpleClaimTypes.UserId);
            entity.LeaveMessageUserName = _currentUser?.FindClaimValue(SimpleClaimTypes.UserName);
            entity.LeaveMessageUserImageId = _currentUser?.FindClaimValue(SimpleClaimTypes.CurrentUserImageId);

            var loginTypeValue = _currentUser?.FindClaimValue(SimpleClaimTypes.LoginType);
            if (!string.IsNullOrWhiteSpace(loginTypeValue))
            {
                Enum.TryParse(typeof(LoginType), loginTypeValue, out var _loginTypeValue);
                if (_loginTypeValue != null)
                {
                    entity.LoginType = ((LoginType)_loginTypeValue).GetHashCode();
                }

                if (((LoginType)_loginTypeValue) == LoginType.ParentSide)
                {
                    //家长端
                    var parent = await (await OrganizationFilter(_context.Set<Parent>())).FirstOrDefaultAsync(c => c.Id == _currentUser.UserId);
                    if (parent != null && parent.ImgId.HasValue && !string.IsNullOrWhiteSpace(entity.LeaveMessageUserImageId))
                    {
                        Guid.TryParse(entity.LeaveMessageUserImageId, out var parentImageId);
                        if (parent.ImgId != parentImageId)
                        {
                            entity.LeaveMessageUserImageId = parent.ImgId.ToString();
                        }
                    }
                }
                else if (((LoginType)_loginTypeValue) == LoginType.GardenSide)
                {
                    //园务端
                    entity.LeaveMessageUserImageId = await _fileInfoService.GetUserPortrait(_currentUser.UserId.Value);
                }
            }

            var relationshipValue = _currentUser?.FindClaimValue(SimpleClaimTypes.Relationship);
            if (!string.IsNullOrWhiteSpace(relationshipValue))
            {
                Enum.TryParse(typeof(EnumParentRelationship), relationshipValue, out var _relationshipValue);
                if (_relationshipValue != null)
                {
                    entity.Relationship = ((EnumParentRelationship)_relationshipValue).GetHashCode();
                }
            }

            var childIdValue = _currentUser?.FindClaimValue(SimpleClaimTypes.ChildId);
            Guid.TryParse(childIdValue, out Guid chidrenId);
            entity.RelationshipChildrenId = chidrenId;

            var classesIdValue = _currentUser?.FindClaimValue(SimpleClaimTypes.ClassesId);
            if (!string.IsNullOrWhiteSpace(classesIdValue))
            {
                Guid.TryParse(classesIdValue, out var _currentClassId);
                entity.ClassId = _currentClassId;
            }

            if (classDynamicInfo.LeaveMessages != null && classDynamicInfo.LeaveMessages.Any())
            {
                classDynamicInfo.LeaveMessages.Add(entity);
            }
            else
            {
                classDynamicInfo.LeaveMessages = new List<ClassDynamicLeaveMessage>() { entity };
            }

            _context.Update(classDynamicInfo);

            var _currentMyLeaveMessageList = (await OrganizationFilter(_context.Set<ClassDynamicLeaveMessage>())).Where(c => c.CreatedUserId == _currentUser.UserId)?.ToList();
            if (_currentMyLeaveMessageList != null && _currentMyLeaveMessageList.Any() && !string.IsNullOrWhiteSpace(entity.LeaveMessageUserImageId))
            {
                _currentMyLeaveMessageList?.ForEach(c =>
                {
                    c.LeaveMessageUserImageId = entity.LeaveMessageUserImageId;
                });

                _context.UpdateRange(_currentMyLeaveMessageList);
            }

            return await _context.SaveChangesAsync(); ;
        }


        public async Task<PageResultModel<MoveClassDynamicOutputModel>> MoveMyClassDynamicGetPageAsync(ClassDynamicQueryPageInputModel input)
        {
            return await CommonMoveGetPageAsync(input, true);
        }

        public async Task<PageResultModel<MoveClassDynamicOutputModel>> CommonMoveGetPageAsync(ClassDynamicQueryPageInputModel input, bool mySelfDynamic = false, int? state = null)
        {

            if (_currentUser == null || !_currentUser.UserId.HasValue)
            {
                throw AppResultException.Status409Conflict("登录过期，请重新登录!");
            }

            var loginTypeValue = _currentUser?.FindClaimValue(SimpleClaimTypes.LoginType);
            LoginType? loginType = null;
            if (!string.IsNullOrWhiteSpace(loginTypeValue))
            {
                loginType = (LoginType)Enum.Parse(typeof(LoginType), loginTypeValue);
            }

            var classIdList = new List<string>();
            if (loginType != null)
            {
                if (loginType == LoginType.GardenSide)
                {
                    //老师
                    var currentClassAuthorizationList = await GetClassAuthorizationInfo();

                    if (currentClassAuthorizationList != null && currentClassAuthorizationList.Any())
                    {
                        classIdList = currentClassAuthorizationList.Select(c => c.Id.ToString() ?? string.Empty).Where(c => !string.IsNullOrWhiteSpace(c)).ToList();
                    }
                }
                else if (loginType == LoginType.ParentSide)
                {
                    //家长
                    var _currentClassId = _currentUser?.FindClaimValue(SimpleClaimTypes.ClassesId);
                    if (!string.IsNullOrWhiteSpace(_currentClassId))
                    {
                        if (_currentClassId?.Contains(',') ?? false)
                        {
                            classIdList = _currentClassId?.Split(',')?.ToList();
                        }
                        else
                        {
                            classIdList.Add(_currentClassId);
                        }
                    }
                }
            }

            if (classIdList == null || !classIdList.Any())
            {
                return new PageResultModel<MoveClassDynamicOutputModel>() { Rows = new List<MoveClassDynamicOutputModel>() };
            }

            var result = new PageResultModel<MoveClassDynamicOutputModel>();
            var query = await OrganizationFilter(_context.Set<ClassDynamic>().Include(c => c.Images).Include(c => c.LeaveMessages).Include(c => c.DynamicLikes));

            if (!string.IsNullOrEmpty(input.ContentKey))
            {
                query = query.Where(m => EF.Functions.Like(m.Content, $"%{input.ContentKey}%"));
            }

            if (!string.IsNullOrWhiteSpace(input.ClassId))
            {
                query = query.Where(m => m.ClassIds.Contains(input.ClassId));
            }

            if (state.HasValue)
            {
                query = query.Where(c => c.State == state);
            }

            if (state.HasValue)
            {
                query = query.Where(c => c.State == state);
            }

            if (mySelfDynamic && _currentUser != null)
            {
                query = query.Where(c => c.CreatedUserId == _currentUser.UserId);
            }

            Expression<Func<ClassDynamic, bool>>? multipleSampleCodeConditions = null;
            if (classIdList.Any())
            {
                multipleSampleCodeConditions = classIdList.Select(no => (Expression<Func<ClassDynamic, bool>>)(x => EF.Functions.Like(x.ClassIds, $"%{no}%")))?.ConcatOr();
            }

            if (multipleSampleCodeConditions != null)
            {
                query = query.Where(multipleSampleCodeConditions);
            }

            // 排序
            query = query.OrderByDescending(m => m.CreatedTime);

            // 获取总数量
            result.TotalRows = await query.CountAsync();

            // 分页查询
            query = query.Page(input.PageNo, input.PageSize);
            var classDynamicOutResultList = await query.ToListAsync();
            result.Rows = MapperHelper.Map<List<MoveClassDynamicOutputModel>>(classDynamicOutResultList);
            if (classDynamicOutResultList != null && classDynamicOutResultList.Any())
            {
                var _classIdList = string.Join(",", classDynamicOutResultList.Select(c => c.ClassIds)).Split(",")?.ToList()?.Distinct()?.Select(c => Guid.Parse(c));
                List<SysClasses>? classList = new List<SysClasses>();
                if (_classIdList != null && _classIdList.Any())
                {
                    classList = _context.Set<SysClasses>().Where(c => _classIdList.Contains(c.Id))?.ToList();
                }

                var leaveMessageChildIdList = classDynamicOutResultList?.SelectMany(c => c.LeaveMessages?.Select(p => p.RelationshipChildrenId) ?? new List<Guid?>())?.Where(c => c != default(Guid)) ?? new List<Guid?>();
                var _childIdList = classDynamicOutResultList?.Where(c => c.RelationshipChildrenId.HasValue).Select(c => c.RelationshipChildrenId)?.Union(leaveMessageChildIdList.Where(c => c != default(Guid)))?.ToList();
                List<Childrens>? chidrenList = new List<Childrens>();
                if (_childIdList != null && _childIdList.Any())
                {
                    chidrenList = _context.Set<Childrens>().Where(c => _childIdList.Contains(c.Id))?.ToList();
                }

                result.Rows?.ForEach(item =>
                {
                    var currentClassIdList = classDynamicOutResultList?.FirstOrDefault(c => c.Id == item.Id)?.ClassIds?.Split(',')?.ToList()?.Select(c => Guid.Parse(c));
                    if (currentClassIdList != null && currentClassIdList.Any())
                    {
                        item.ClassList = classList?.Where(c => currentClassIdList.Contains(c.Id))?.ToList()?.Select(c => new ClassDynamicSysClassesDto { ClassId = c.Id.ToString(), ClassName = c.Name })?.ToList() ?? new List<ClassDynamicSysClassesDto>();
                    }
                    item.RelationshipChildrenName = chidrenList?.FirstOrDefault(p => p.Id == item.RelationshipChildrenId)?.Name ?? string.Empty;
                    item.LeaveMessages = item.LeaveMessages?.Where(c => c.IsPublish)?.ToList();
                    item.LeaveMessages?.ForEach(l =>
                    {
                        l.RelationshipChildrenName = chidrenList?.FirstOrDefault(p => p.Id == l.RelationshipChildrenId)?.Name ?? string.Empty;
                    });
                    item.IsLike = item.DynamicLikes.Any(p => p.ParentOrTeacherId == _currentUser.UserId.Value);
                });
            }

            result.SetPage(input);
            result.CountTotalPage();

            return result;
        }
    }
}
